//PROFIL
$(document).ready(function(){
	$("#savePassword").click(function(){
		$.post("/users/update_password", { password: $("#password1").val(), password_confirmation: $("#password2").val()}, function(data){
			if(data != "0"){
				showDialog("error", "Fehler", data);
			}
			else{
				showDialog("notice", "Kennwort ge&auml;ndert", "Ihr Kennwort wurde erfolgreich ge&auml;ndert.");
			}
		});
	});
	
	$("#edit").click(function(event){
		if($("#savePro").val() != "Speichern"){
			event.preventDefault();
			$.get("/users/change_profile", function(data){
				$("#profileDetail").html(data);
				$("#edit").val("Speichern");
				$("#edit").attr("name", "savePro");
				$("#edit").attr("id", "savePro");
			});
		}else{
			$.post("/users/update_profile", { name: $("#name").val(), email: $("#email").val()}, function(data){
				if(data != "0"){
					showDialog("error", "Fehler", data);
				}
				else{
					$("#new_painting").submit();
				}
			});
		}
	});
});


//USERUEBERSICHT
$(document).ready(function(){
	$("#dedicated_employees").parent().children("ul").hide();
	
	$(".projects").parent().children("ul").each(function(){
		$(this).hide();
	});
	
	$("#singleuser").load('../users/new', function(){
		$(".project_assignment").hide();
	});
	
	$("#dedicated_employees").click(function(){
		$(this).parent().children("ul").slideToggle();
	});
	
	$("#undedicated_employees").click(function(){
		$(this).parent().children("ul").slideToggle();
	});
	
	$(".projects").click(function(){
		$(this).parent().children("ul").slideToggle();
	});
	
	$("#addUser").click(function(){
		$("#singleuser").load('/users/new', function(){
			$(".project_assignment").hide();
		});
	});
	
    //Event für den Auswahlmodus registrieren.
    chooseMode("#selectUser", "#chooseModeIcon");
	
	var single_ma_id="";
	var markedUsers = new Array();
	$( document ).on("click", ".mitarbeiter", function(){
		// var parts = this.id.split("_");
		var parts = $(this).children("a").attr("class").split("_");
		
		// single_ma_id = this.id.split("_")[1];
		single_ma_id = parts[1];
		var id = parts[1];
		if(chooseModus){
			if ( $.inArray(id, markedUsers) >= 0 ){
				markedUsers.splice($.inArray(id, markedUsers), 1);
				// $("#"+parts[0]+"_"+parts[1]).removeClass("marked");
				$("."+parts[0]+"_"+parts[1]).removeClass("marked");
			}
			else{
				markedUsers.push(id);
				// $("#"+parts[0]+"_"+parts[1]).addClass("marked");
				$("."+parts[0]+"_"+parts[1]).addClass("marked");
			}
		}
		else{
			// wenn nicht im Auswahlmodus, einzelnen Mitarbeiter
			// laden und im Controller Zuornungstabelle herstellen
			$("#singleuser").load('/users/edit?id='+id, function(){
				$('.project_assignment').hide();	
				$.get('/project_to_users/edit?id='+id, function(data){
					if( data != "" ){
						$('.project_assignment').show();	
						$("#assignment_table tbody").append(data);
					}
				});
			});
		}
	});
	
	$("#deleteUser").click(function(){	
		showDialog('warning', "L&ouml;schen der User/Users", "Der / Die User/Users werden unwiederruflich gelöscht.<p><a href=\"javascript:void(null)\" id=\"confirmDelete\"><img alt=\"confirmIcon\" class=\"icon\" id=\"confirmIcon\" src=\"/assets/layout/OK.png\"/> Best&auml;tigen</a><a href=\"javascript:void(null)\" id=\"cancel\" class=\"closeButton\"><img alt=\"cancelIcon\" class=\"icon\" id=\"cancelIcon\" src=\"/assets/layout/Cancel.png\"/> Abbrechen</a></p>");
	});
	
	$(document).on("click", "#confirmDelete", function(){
		var items ="";
		$("#shader").hide();
		if(chooseModus){
			// mehrere ausgewählte nutzer löschen
			markedUsers.forEach(function(element){
				items += element+",";
			});
			items = items.substring(0, items.length-1);
		}
		else{
			items = single_ma_id;
		}
		
		$.getJSON("../users/delete?items="+items).done(function(data){
			if( data == "" ){	
				$.getJSON("../project_to_users/delete?items="+items).done(function(data){
					if ( data == 1){
						rem = items.split(",");
						for( var i=0; i < rem.length; i++ ){
							removeEmployee( "employee_"+rem[i] );
						}
					}
					else{
						alert("delete ptu error");
					}
				});
			}
			else{
				alert("Delete Fail for Users: "+data);
				// Die erfolgreichen rausfiltern und noch löschen.
			}
		});
	});
	
	showOrHide("#userMenu #showHideKey", "#keys", "Die Legende ausblenden", "Die Legende einblenden", "#showHideKey", "#userStoryList", 24);
	
	$(document).on("click", "#add_assignment", function(){
		if(!$(".project_assignment").is(":visible")){
			$(".project_assignment").show();
		}
		
		$.get("../project_to_users/new",function(data){
			$("#assignment_table").append(data);
			var rowCount = $('#assignment_table tr').length;
			rowCount = rowCount-2;
			$("#row").attr("id", "row_"+rowCount);
		});
	});	
	
	$(document).on("click", "#create_user", function(){
		var request = "";
		var email = $("#user_email").val();
		var name = $("#user_name").val();
		
		request = name + "," + email;
		$.getJSON("../users/create?items="+request).done(function(userid){
			if( userid != 0)
			{
				// zugehörige projekte anlegen
				var projects = userid + "," + getProjectAssignment();
				$.getJSON("../project_to_users/create?items="+projects).done(function(data){
					if( data == 1 ){
						var assignments = projects.split(",");
						var offset = 2;
						var setlen = 3;
						var load = 0;
						for (var i = 0; i < assignments[1]; i++){
							assignEmployeeToProject(userid,name,assignments[offset+i*setlen],assignments[offset+i*setlen+1],assignments[offset+i*setlen+2]);
							load = load + parseInt(assignments[offset+i*setlen+2]);
						}
						assignEmployeeNotOrOverload(userid,name,load);
					}
					else{
						showDialog("error", "Fehler beim Anlegen der Zuordnung!", "Es konnte nicht gespeichert werden.");						alert("error on ptu");
					}
				});
			}
			else
			{
				showDialog("error", "Fehler beim Anlegen des Benutzers!", "Es konnte nicht gespeichert werden.");
			}
		});
	});
	
	$(document).on("click", "#update_user", function(){
		var name = $("#user_name").val();
		var id = $("#user_id").val();
		
		var projects = id + "," + getProjectAssignment();
		$.getJSON("../project_to_users/update?items="+projects).done(function(data){
			if( data == 1 ){
				var rem_id = id.split("_")[1];
				removeEmployee("employee_"+rem_id);
				projects = name + "," + projects;
				assignEmployeeToProjects(projects);
			}
			else{
				showDialog("error", "Fehler beim Aktualisieren des Benutzers!", "Es konnte nicht gespeichert werden.");
			}
		});
	});
	
	$(document).on("click", ".delete_assignment_icon", function(){
		$(this).parent().parent().remove();
		var rowCount = $('#assignment_table > tbody > tr').length;
		if(rowCount==0){
			$('#assignment_table').hide();
		}
	});
});

function getProjectAssignment()
{
	var rowCount = $('#assignment_table > tbody > tr').length;
	var elem = $('#assignment_table > tbody > tr');
	var request = "";
	
	//elem.each(function(index){
	//	request += "," + $(this).find("td .projectclass").val(); 
	//	request += "," + $(this).find("td .roleclass").val();
	//	request += "," + $(this).find("td .percentclass").val();
	//});
	
	var proj = 0;
	var role = 0;
	var percent = 0;
	var projArr = new Array();
	var roleArr = new Array();
	var percentArr = new Array();
	elem.each(function(index){
		proj = $(this).find("td .projectclass").val(); 
		role = $(this).find("td .roleclass").val();
		percent = $(this).find("td .percentclass").val();
		
		var posproj = isIdInArray(projArr, proj);
		var posrole = isIdInArray( roleArr, role );
		
		if( posproj != -1 && posrole != -1 && posproj == posrole ){
			percent = parseInt(percentArr[posproj]) + parseInt(percent);
			percent = percent.toString();
			percentArr.splice(posproj,1, percent);
			rowCount--;
		}
		else{
			projArr.push(proj);
			roleArr.push(role);
			percentArr.push(percent);
		}
	});
	
	request = rowCount;
	for(var i=0; i<projArr.length; i++){
		request += "," + projArr[i];
		request += "," + roleArr[i];
		request += "," + percentArr[i];
	}
		
	return request;
}

function isIdInArray(someIntArray, int){
	var pos = -1;
	var len = someIntArray.length;
	if( len == 0 ){
		return pos;
	}
	
	for(var i=0; i<len; i++){
		if ( someIntArray[i] == int ){
			pos = i;
		} 
	}
	return pos;
}

function assignEmployeeToProjects(projects){
	// name, id, rows, zuordnungen
	var assignments = projects.split(",");
	var rows = assignments[2];
	var name = assignments[0];
	var id = assignments[1].split("_")[1]; 
	var offset = 3;
	var datasetlen = 3;
	var load = 0;
	for( var i = 0; i < rows; i++ ){
		assignEmployeeToProject( id, name, assignments[offset+i*datasetlen],assignments[offset +i*datasetlen+ 1], assignments[offset +i*datasetlen+ 2] );
		load = parseInt(assignments[offset +i*datasetlen+ 2]) + load;
	}
	assignEmployeeNotOrOverload(id,name,load);
}

function assignEmployeeToProject(userid,username,project,role,percentage){
	var selector = "";
	selector = "#project_" + project;
	var classname = "";
	switch(role){
	case "1":
		classname = "productowner";
		break;
	case "2":
		classname = "scrummaster";
		break;
	case "3": 
		classname = "developer";
		break;
	default:
		break;
	}
	var percent = parseInt(percentage)*10;
	var daten = "<li class='mitarbeiter'><div class='"+classname+"'></div> <a href='javascript:void(null)' class='employee_"+userid+"'>" + username + " ("+percent+"%)</a></li>";
	$(selector).append(daten);					
}

function assignEmployeeNotOrOverload(userid,username,percentage){
	var selector = "";
	var percent = parseInt(percentage)*10;
	if ( percent < 100 ){
		selector ="#underload_employees";
	}
	if ( percent > 100 ){
		selector ="#overload_employees";
	}
		
	var daten ="<li class='mitarbeiter'><a href='javascript:void(null)' class='employee_"+userid+"'>"+username+" ("+percent+"%)</a></li>";	
	$(selector).append(daten);
}

function removeEmployee(id){
	$("a[class='"+id+"']").parent().remove();
}